package crp.infra.ipinfo;

import com.google.common.base.Splitter;
import crp.core.analysis.domain.models.IpInfo;
import crp.core.analysis.domain.models.Loc;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;

import java.util.List;
import java.util.stream.Collectors;

@Getter
@Setter
@Builder
public class IpInfoResponse {
    private String ip;
    private String city;
    private String region;
    private String country;
    private String loc;
    private String org;
    private String timezone;

    public Loc ofLoc() {
        List<Float> rawLoc = Splitter.on(",")
                .trimResults()
                .splitToStream(this.loc)
                .map(value -> {
                    try {
                        return Float.parseFloat(value);
                    } catch (Exception e) {
                        return null;
                    }
                })
                .limit(2)
                .collect(Collectors.toList());
        rawLoc.add(null);
        return Loc.builder()
                .longitude(rawLoc.get(0))
                .latitude(rawLoc.get(1))
                .build();
    }

    public IpInfo ofIpInfo() {
        return IpInfo.builder()
                .ip(ip)
                .city(city)
                .region(region)
                .country(country)
                .loc(ofLoc())
                .org(org)
                .timezone(timezone)
                .build();

    }
}
